package com.yr.ryjk.consult.autoend;

import java.util.Iterator;
import java.util.Map;
import java.util.TimerTask;

import javax.servlet.ServletContext;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.yr.ryjk.common.Constant;
import com.yr.ryjk.consult.service.ConsultService;
import com.yr.ryjk.consult.service.IConsultService;
import com.yr.ryjk.jpush.JPushType;
import com.yr.ryjk.redis.JedisUtil;
import com.yr.ryjk.util.SpringMVCUtils;

/**
 * 自动确认咨询的定时任务器
 * @author Rick
 *
 */
public class ConsultAutoEndTask extends TimerTask{
	private IConsultService consultService;
	private Logger logger=Logger.getLogger(this.getClass());
	
	@SuppressWarnings("deprecation")
	public ConsultAutoEndTask(ServletContext servletContext) {
		consultService=(IConsultService) SpringMVCUtils.getBeanByName(servletContext,
				StringUtils.uncapitalise(ConsultService.class.getSimpleName()));
		System.out.println(consultService==null);
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void run() {
		System.out.println("run()....");
		Map<String, String> map = JedisUtil.getConsultTimerMap();
		Iterator it = map.entrySet().iterator();
		while (it.hasNext()) {
			Map.Entry entry = (Map.Entry) it.next();
			String consultId = (String) entry.getKey();
			long time = Long.parseLong(entry.getValue().toString());
			if(isTimeOver(time)){
				logger.info("咨询id："+consultId+",时间"+time+"满足,启动自动确认...");
				consultService.updateEnd(consultId,JPushType.count_down_end);
			}else {
				logger.info("咨询id："+consultId+",时间"+time+"不满足...");
			}
		}
	}
	
	/**
	 * 判断倒计时是否已经完毕
	 * @param time
	 * @return
	 */
	private boolean isTimeOver(long time){
		int countdown=Constant.consult_countdown_time;  //咨询倒计时时间
		long now=System.currentTimeMillis();            //现在
		return now-time>=countdown;
	}
}